package nancal.mp.service.jenkins

import nancal.mp.db.mongo.entity.dev.AppDeploySetting
import nancal.mp.db.mongo.entity.dev.JenkinsOpsLog
import nancal.mp.db.mongo.extend.getAppDeploySetting
import nancal.mp.db.mongo.mor
import nancal.mp.service.K8sDeploymentService
import nbcp.base.extend.*
import nbcp.base.utils.SpringUtil
import nbcp.base.utils.UrlUtil
import org.slf4j.LoggerFactory
import java.time.LocalDateTime


data class ImageNameVersionData(
    var name: String = "",
    var fullImageVersion: String = ""
)

class JenkinsExportModel : JenkinsOpsLog() {

    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
        fun loadFrom(ent: JenkinsOpsLog): JenkinsExportModel {
            return ent.ConvertJson(JenkinsExportModel::class.java);
        }
    }


    private var _k8sServiceImages: List<ImageNameVersionData>? = null;
    val k8sServiceImages: List<ImageNameVersionData>
        get() {
            if (_k8sServiceImages != null) {
                return _k8sServiceImages!!;
            }

            var task = this;
            if (task.k8sServices.HasValue) {
                var k8sService = SpringUtil.getBean<K8sDeploymentService>();
                var res = task.k8sServices.map {

                    var r = k8sService.getDeploymentInfo(
                        task.targetEnv,
                        task.namespace,
                        it
                    )
                    if (r.hasError) {
                        throw RuntimeException(r.msg)
                    }

                    return@map r.data!!
                };


                _k8sServiceImages =
                    res.map { ImageNameVersionData(it.name, it.fullImageVersion) }


                logger.warn("k8s服务: " + task.k8sServiceImages.ToJson())
                return _k8sServiceImages!!;
            }

            return listOf()
        }
}

class JenkinsOpsExportJob(
    val task: JenkinsExportModel = JenkinsExportModel()
) {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    val appDeploySetting: AppDeploySetting
        get() {
            return mor.dev.appDeploySetting.getAppDeploySetting(task.targetEnv)
        }


    fun docker_pull_services(): String {
        return """
echo -e `date "+%Y-%m-%d %H:%M:%S"` 拉取镜像
        
source docker_save.sh

""" +
                this.task.k8sServiceImages.map {
                    """ 
echo  docker_save   ${it.name}  ${it.fullImageVersion}
docker_save   ${it.name}  ${it.fullImageVersion}

"""
                }.joinToString("\n") +
                """

echo ${LocalDateTime.now().AsString()} > k8s-ops/report-${LocalDateTime.now().Format("MMdd")}.txt
"""
    }


    fun split_tar(): String {
        return """
echo -e `date "+%Y-%m-%d %H:%M:%S"` 拆包

echo  tar -czvf k8s-ops.tar.gz k8s-ops
${this.appDeploySetting.sudo} tar -czvf k8s-ops.tar.gz k8s-ops

echo  split -d  -b ${task.size}M  k8s-ops.tar.gz  ./k8s-ops-split/k8s-ops-
${this.appDeploySetting.sudo} split -d  -b ${task.size}M  k8s-ops.tar.gz  ./k8s-ops-split/k8s-ops-

echo 拆包完成

mv  install.sh  ./k8s-ops-split/
"""

    }

    fun upload_minio(): String {
        return """

source upload_minio.sh

for file in `ls ./k8s-ops-split`
do
    upload_minio  k8s-ops-split/＄file
done

"""
    }


    fun mongo_dump(): String {
        if (!task.mongo.isValidate()) {
            return "echo 跳过mongo备份";
        }

        return """
echo -e `date "+%Y-%m-%d %H:%M:%S"` 备份mongo数据库

source mongo_dump.sh

${
            task.mongo.dbs.split(",")
                .map {
                    """
echo mongo_dump ${task.mongo.host} ${task.mongo.port} ${task.mongo.user} ${task.mongo.password} ${it}
mongo_dump ${task.mongo.host} ${task.mongo.port} ${task.mongo.user} ${task.mongo.password} ${it}

"""
                }
                .joinToString("\n")
        }

"""
    }


    fun mongo_mysql(): String {
        if (!task.mysql.isValidate()) {
            return "echo 跳过mysql备份";
        }

        return """
echo -e `date "+%Y-%m-%d %H:%M:%S"` 备份mysql数据库

source mysql_dump.sh

${
            task.mysql.dbs.split(",")
                .map {
                    """
echo mysql_dump ${task.mysql.host} ${task.mysql.port} ${task.mysql.user} ${task.mysql.password} ${it}
mysql_dump ${task.mysql.host} ${task.mysql.port} ${task.mysql.user} ${task.mysql.password} ${it}

"""
                }
                .joinToString("\n")
        }

"""
    }

    fun getExportPipeline(): String {
        if (this.task.id.isNullOrEmpty()) {
            throw RuntimeException("找不到任务信息");
        }

        return """
pipeline {
    agent any
    environment {
        jobName = "导出"
    }
    stages {
        stage('拉取镜像') {
            steps {
            ${
            """
echo -e `date "+%Y-%m-%d %H:%M:%S"` 准备环境
sudo chmod a+rw ./ -R
sudo rm -rf * 

mkdir -p k8s-ops/docker && mkdir -p k8s-ops/mongo && mkdir -p k8s-ops-split

echo curl ${appDeploySetting.mpIntegrationApiUrl}/ops/jenkins-ops/cmd/file/${task.id}?admin-token=${UrlUtil.encodeURIComponent(appDeploySetting.adminToken)} -o .ops-cmd.zip
curl ${appDeploySetting.mpIntegrationApiUrl}/ops/jenkins-ops/cmd/file/${task.id}?admin-token=${UrlUtil.encodeURIComponent(appDeploySetting.adminToken)} -o .ops-cmd.zip

echo unzip -q -o -d ./  .ops-cmd.zip
unzip -q -o -d ./  .ops-cmd.zip 


""".sudoExecSh()
        }
            
${
            docker_pull_services().sudoExecSh()
        }

            }
        }
        stage('备份mongo库') {
            steps {
           
${mongo_dump().sudoExecSh()}

            }
        }
        
       stage('备份mysql库') {
            steps {
           
${mongo_mysql().sudoExecSh()}

            }
        }
        
        stage('拆包') {
            steps {
${split_tar().sudoExecSh()}
            }
        }
    }
} 
"""
    }

}